/**
 * 目录：
 * 1. 全局变量定义
 * 2. 网站相关方法
 * 3. 收藏夹相关方法
 * 4. 权限相关方法
 * 5. Toast 相关方法
 * 6. 用户相关方法
 * 7. 生命周期
 * 8. 返回数据
 */

const { createApp, ref, computed, onMounted } = Vue;

const app = createApp({
    setup() {
        /// ==================== 全局变量定义 ====================

        //. Token
        let token = localStorage.getItem('token') || null;
        //. Base URL
        const BASE_URL = baseUrl; //. 这里是从url.js引入的baseUrl
        //. 默认headers
        axios.defaults.headers.common['Authorization'] = token;

        //. 默认用户信息
        const defaultUser = {
            id: 0,
            username: '游客',
            phone: '',
            permission: 0,
            recorddate: '',
            email: '',
            logintime: '',
            collection: ''
        };

        //. 当前用户信息
        const currentUser = ref(defaultUser);


        /// ==================== 网站相关方法 ====================
        //. 网站数据
        const sites = ref([]);

        //. 获取网站数据
        const fetchSites = async () => {
            try {
                const response = await axios.get(`${BASE_URL}/data/getDataByDimName`);
                sites.value = response.data.data;
            } catch (error) {
                console.error('获取网站数据失败:', error);
            }
        };

        //. 当前选择的分类
        const selectedCategory = ref('all');

        //. 获取全部分类名称
        const categories = computed(() => {
            const uniqueCategories = new Set(sites.value.map(site => site.group));
            return Array.from(uniqueCategories);
        });

        //. 过滤网站
        const filteredSites = computed(() => {
            //. 首先根据权限过滤,这里储存的是全部数据下面继续过滤
            let filtered = sites.value.filter(site =>
                currentUser.value && currentUser.value.permission >= site.permission
            );

            //. 如果显示收藏夹，只显示收藏的内容
            if (showFavorites.value) {
                filtered = filtered.filter(site =>
                    favorites.value.some(fav => fav.id === site.id)
                );
            }

            //. 如果选择了特定分类，且不是"全部"，则过滤该分类
            if (selectedCategory.value !== 'all') {
                filtered = filtered.filter(site => site.group === selectedCategory.value);
            }

            return filtered;
        });

        //. 切换分类
        const changeCategory = (category) => {
            selectedCategory.value = category.target.value;
        };

        /// ==================== 收藏夹相关方法 ====================

        //. 收藏夹数据
        const favorites = ref([]);

        //. 收藏夹显示状态
        const showFavorites = ref(false);

        //. 获取收藏夹数据
        const fetchFavorites = async () => {
            try {
                const response = await axios.get(`${BASE_URL}/Fav/getFavData`);
                if (response.data.data == null) {
                    favorites.value = []; //. 如果没有收藏夹数据，设置为空数组
                    return;
                }
                favorites.value = response.data.data;
            } catch (error) {
                console.error('获取收藏夹数据失败:', error);
            }
        };

        //. 切换收藏状态
        const toggleFavorite = (site) => {
            site.isFavorite = !site.isFavorite;
        };

        //. 切换收藏夹显示
        const toggleFavorites = () => {
            if (favorites.value.length === 0) {
                showToast('空空如也', 'info');
                return;
            }
            showFavorites.value = !showFavorites.value;
            showToast(showFavorites.value ? '显示收藏夹' : '显示全部', 'info');
        };

        //. 添加收藏
        const addToFavorites = async (site) => {
            try {
                const response = await axios.post(`${BASE_URL}/Fav/addToFav`, {},
                    {
                        params: {
                            dataId: site.id
                        }
                    }
                );

                if (response.data.code === 200) {
                    //. 更新收藏夹数据
                    favorites.value.push(site);
                    showToast('收藏成功', 'success');

                } else if (response.data.code === 403) {
                    if (showFavorites.value) {
                        await removeFromFavorites(site); //. 取消收藏
                    } else {
                        showToast('收藏失败，已存在收藏夹', 'error');
                    }
                }
            } catch (error) {
                showToast('收藏失败，请稍后再试', 'error');
                console.error('收藏失败:', error);
            }
        };

        //. 取消收藏
        const removeFromFavorites = async (site) => {
            try {
                const response = await axios.delete(`${BASE_URL}/Fav/removeFavData`,
                    {
                        params: {
                            dataId: site.id
                        }
                    }
                );

                if (response.data.code === 200) {
                    //. 更新收藏夹数据
                    favorites.value = favorites.value.filter(fav => fav.id !== site.id);
                    showToast('移除收藏', 'success');
                    if (favorites.value.length === 0) {
                        showFavorites.value = false; //. 隐藏收藏夹
                    }
                } else {
                    showToast(response.data.message, 'error');
                }
            } catch (error) {
                showToast('移除收藏失败，请稍后再试', 'error');
                console.error('移除收藏失败:', error);
            }
        };

        /// ==================== 权限相关方法 ====================
        //. 获取权限文本
        const getPermissionText = (permission) => {
            const permissionMap = {
                0: '游客',
                1: '用户',
                2: '会员',
                3: '管理员',
                4: '超级管理员',
                5: '开发者'
            };
            return permissionMap[permission] || '未知';
        };

        //. 获取权限对应的 CSS 类名
        const getPermissionClass = (permission) => {
            const classMap = {
                0: 'visitor',
                1: 'user',
                2: 'member',
                3: 'admin',
                4: 'super-admin',
                5: 'developer'
            };
            return classMap[permission] || 'visitor';
        };

        //. 是否是小屏幕设备
        const isMobile = ref(false);

        //. 核心检测逻辑
        const detect = () => {
            const ua = navigator.userAgent || navigator.vendor || window.opera;
            const hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
            const screenWidth = window.innerWidth || document.documentElement.clientWidth;

            //. 用户代理检测（覆盖主流移动设备）
            const uaPattern = /(android|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|harmony)/i;

            //. 组合判断条件
            isMobile.value = uaPattern.test(ua) && (hasTouch || screenWidth < 768);
        };


        /// ==================== Toast 相关方法 ====================

        //. Toast 状态
        const toast = ref({
            show: false,
            message: '',
            type: 'info'
        });

        //. 存储定时器ID
        let toastTimer = null;

        //. 存储所有活动的弹窗
        const activeToasts = new Set();

        //. 显示 Toast 的函数
        const showToast = (message, type = 'info') => {
            // 创建新的 Toast 元素
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.classList.add(type);
            toast.textContent = message;

            //. 创建独立的容器
            const container = document.createElement('div');
            container.className = 'toast-container';
            container.appendChild(toast);
            document.body.appendChild(container);

            //. 添加到活动弹窗集合
            activeToasts.add(toast);

            //. 触发重排以启动动画
            toast.offsetHeight;

            //. 设置定时器
            const timer = setTimeout(() => {
                //. 添加消失动画
                toast.style.animation = 'slideUpOut 0.3s ease forwards';

                //. 动画结束后移除元素
                toast.addEventListener('animationend', () => {
                    container.remove();
                    activeToasts.delete(toast);
                });
            }, 3000);

            //. 存储定时器ID
            toast.dataset.timerId = timer;
        };

        /// ==================== 用户相关方法 ====================
        //. 登录
        const login = () => {
            window.location.href = './view/login/login.html';
        };

        //. 退出登录
        const logout = () => {
            currentUser.value = defaultUser;
            token = null;
            localStorage.removeItem('token');
            showToast('退出成功', 'success');
        };

        //. 获取用户信息
        const fetchUserInfo = async () => {
            if (!token) {
                currentUser.value = defaultUser;
                return;
            }

            try {
                const response = await axios.post(`${BASE_URL}/user/getUserByToken`);

                if (response.data.code === 200) {
                    currentUser.value = response.data.data;
                } else {
                    currentUser.value = defaultUser;
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                currentUser.value = defaultUser;
            }
        };

        //. 去后台
        const goToAdmin = () => {
            if (currentUser.value.permission >= 3) {
                window.location.href = './view/taskManager/dataManager.html';
            } else {
                showToast('权限不足', 'error');
            }
        };

        /// ==================== 生命周期 ====================

        //. 页面加载完成后获取用户信息
        onMounted(() => {
            fetchUserInfo(); //. 获取用户信息
            fetchSites(); //. 获取网站数据
            fetchFavorites(); //. 获取收藏夹数据
            detect(); //. 检测设备类型
        });

        /// ==================== 返回值 ====================
        return {
            /// ==================== 网站相关变量 ====================
            filteredSites,
            categories,
            selectedCategory,
            changeCategory,

            /// ==================== 收藏夹相关变量 ====================
            favorites,
            showFavorites,
            toggleFavorites,
            addToFavorites,
            toggleFavorite,

            /// ==================== 权限相关变量 ====================
            getPermissionText,
            getPermissionClass,
            isMobile,

            /// ==================== Toast 相关变量 ====================
            toast,
            showToast,

            /// ==================== 用户相关变量 ====================
            currentUser,
            login,
            logout,
            goToAdmin
        };
    }
});

app.mount('#app');

/**
 * 目录：
 * 1. 全局变量定义
 * 2. 网站相关方法
 * 3. 收藏夹相关方法
 * 4. 权限相关方法
 * 5. Toast 相关方法
 * 6. 用户相关方法
 * 7. 生命周期
 * 8. 返回数据
 */